package org.aom.litebean.frontservice.findpw;

import org.aom.entity.security.User;
import org.aom.litebean.module.base.BeforeRenderBaseBean;
import org.aom.model.FindPWUser;
import org.aom.service.security.IUserManager;
import org.aom.util.MD5Util;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.ManagedProperty;
import org.operamasks.faces.annotation.Required;
import org.operamasks.faces.annotation.Transactional;
import org.operamasks.faces.annotation.ValidateRegexp;
import org.operamasks.faces.util.Browser;
import org.operamasks.faces.validator.CommonRegexpPatterns;

@ManagedBean(name = "frontservice.findpw.findpwBean", scope = ManagedBeanScope.REQUEST)
public class FindpwBean extends BeforeRenderBaseBean {


	@ManagedProperty("#{userManager}")
	private IUserManager userManager;

	@Required(message = "#{this.messages.nameIsRequired}")
	@Bind(id = "username", attribute = "value")
	private String username;

	@Bind(id = "email", attribute = "value")
	@Required(message = "#{this.getMessages().get('required')}")
	@ValidateRegexp(value = CommonRegexpPatterns.EMAIL_ADDRESS, message = "邮件格式错误")
	private String email;

	@Action(id = "findpw")
	public void findpw() {
		User user = userManager.findUserByLoginName(username);
		if (validate(user)) {
			if (sendMail(user)) {
				Browser.execClientScript("window.alert('邮件已发送，请您注意查收！');");
				return;
			} else {
				Browser.execClientScript("window.alert('邮件发送错误！');");
				return;
			}
		}
	}

	private boolean validate(User user) {
		if (user == null || user.getEnable() == 0) {
			Browser.execClientScript("window.alert('您所输入的用户不存在或已被禁用！');");
			return false;
		} else if (!email.trim().equals(user.getEmail().trim())) {
			Browser.execClientScript("window.alert('请您确认找回密码所用邮箱的正确性!');");
			return false;
		}
		return true;
	}

	@Transactional
	private boolean sendMail(User user) {
		String newPw = user.getPassword().substring(1, 16);
		user.setPassword(MD5Util.getMd5PasswordEncoder(newPw, user
				.getLoginName()));
		user.setExpTime(System.currentTimeMillis() + 48 * 60 * 60 * 1000);
		userManager.save(user);
		FindPWUser findPWUser = new FindPWUser(user.getName(), newPw, user
				.getEmail());
		try {
			userManager.sendNotifyMessage(findPWUser);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	@BeforeRender
	protected void beforeRender(boolean isPostBack) {
	}
}
